package com.itwn.email.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class EmailListener {

    @Autowired
    private JavaMailSender mailSender;

    /**
     * @RabbitListener 监听队列
     *   queues 指定队列名称，队列必须要存在
     */
    @RabbitListener(queues = "email.queue")
    public void sendEmail(Map<String,String> map) {
        // 获取消息内容数据
        String from = map.get("from");
        String to = map.get("to");
        String subject = map.get("subject");
        String content = map.get("content");
        log.info("消息监听器：发邮件：" + from + "->" + to + "，主题：" + subject + "，内容：" + content);

        // 构造邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject(subject);
        message.setText(content);
        message.setFrom(from);
        message.setTo(to);

        // 发邮件
        mailSender.send(message);

    }
}
